import router from '@/router'
import { useUserStore } from '@/stores'
import axios from 'axios'




const request = axios.create({
  baseURL: 'https://api-hmzs.itheima.net/v1',
  timeout: 5000 // request timeout
})
// 请求拦截器
request.interceptors.request.use(
    config => {
        const store = useUserStore()
        if (store.token) {
            config.headers.Authorization =`Bearer ${store.token}`
        }
    return config
  },
  error => {
    return Promise.reject(error)
  }
)

// 响应拦截器
request.interceptors.response.use(
  response => {
    return response.data
  },
    error => {
        if (error.response.status === 401) {
            const store = useUserStore()
            router.push('/login')
          store.del()
      }
    return Promise.reject(error)
  }
)

export default request